<template>
  <div class="offspring-list">
    <h2 class="page-title">Offspring Tracking Management</h2>

    <!-- Search and Filter -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="Donor">
          <el-select
            v-model="searchForm.donor_id"
            placeholder="Select donor"
            clearable
            filterable
            style="width: 260px"
          >
            <el-option
              v-for="donor in donorList"
              :key="donor.donor_id"
              :label="`${donor.donor_code} - ${donor.full_name}`"
              :value="donor.donor_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="Gender">
          <el-select v-model="searchForm.gender" placeholder="Select gender" clearable style="width: 150px">
            <el-option label="Male" value="Male" />
            <el-option label="Female" value="Female" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            Search
          </el-button>
          <el-button @click="handleReset">Reset</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- Action Bar -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>Offspring List</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            Add Offspring Record
          </el-button>
        </div>
      </template>

      <!-- Table -->
      <el-table
        v-loading="loading"
        :data="offspringList"
        style="width: 100%"
      >
        <el-table-column prop="offspring_id" label="ID" width="60" />
        <el-table-column prop="donor_code" label="Donor Code" width="120" />
        <el-table-column prop="donor_name" label="Donor Name" width="120" />
        <el-table-column prop="recipient_name" label="Recipient Name" width="120" />
        <el-table-column prop="date_of_birth" label="Date of Birth" width="120">
          <template #default="{ row }">
            {{ formatDate(row.date_of_birth) }}
          </template>
        </el-table-column>
        <el-table-column prop="gender" label="Gender" width="80" />
        <el-table-column prop="reported_by" label="Reported By" width="160" show-overflow-tooltip />
        <el-table-column prop="report_date" label="Report Date" width="140">
          <template #default="{ row }">
            {{ formatDate(row.report_date) }}
          </template>
        </el-table-column>
        <el-table-column label="Actions" width="230">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">
              Edit
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)">
              Delete
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- Pagination -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handlePageChange"
        @current-change="handlePageChange"
        style="margin-top: 20px; justify-content: flex-end;"
      />
    </el-card>

    <!-- Add/Edit Dialog -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item label="Donor" prop="donor_id">
          <el-select
            v-model="formData.donor_id"
            placeholder="Select donor"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="donor in donorList"
              :key="donor.donor_id"
              :label="`${donor.donor_code} - ${donor.full_name}`"
              :value="donor.donor_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="Recipient" prop="recipient_id">
          <el-select
            v-model="formData.recipient_id"
            placeholder="Select recipient"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="recipient in recipientList"
              :key="recipient.recipient_id"
              :label="recipient.full_name"
              :value="recipient.recipient_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="Date of Birth" prop="date_of_birth">
          <el-date-picker
            v-model="formData.date_of_birth"
            type="date"
            placeholder="Select date"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="Gender" prop="gender">
          <el-radio-group v-model="formData.gender">
            <el-radio label="Male">Male</el-radio>
            <el-radio label="Female">Female</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="Reported By" prop="reported_by">
          <el-input v-model="formData.reported_by" placeholder="Enter reporting organization name" />
        </el-form-item>
        <el-form-item label="Report Date" prop="report_date">
          <el-date-picker
            v-model="formData.report_date"
            type="date"
            placeholder="Select date"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="handleSubmit">Confirm</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus } from '@element-plus/icons-vue'
import { offspringAPI, donorAPI, recipientAPI } from '@/api'

const route = useRoute()

// Search form
const searchForm = reactive({
  donor_id: '',
  gender: ''
})

// Pagination
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// Data lists
const offspringList = ref([])
const donorList = ref([])
const recipientList = ref([])
const loading = ref(false)

// Dialog
const dialogVisible = ref(false)
const dialogTitle = ref('Add Offspring Record')
const formRef = ref(null)
const formData = reactive({
  offspring_id: null,
  donor_id: '',
  recipient_id: '',
  date_of_birth: '',
  gender: 'Male',
  reported_by: '',
  report_date: new Date()
})

// Form validation rules
const formRules = {
  donor_id: [{ required: true, message: 'Please select donor', trigger: 'change' }],
  recipient_id: [{ required: true, message: 'Please select recipient', trigger: 'change' }],
  date_of_birth: [{ required: true, message: 'Please select date of birth', trigger: 'change' }],
  gender: [{ required: true, message: 'Please select gender', trigger: 'change' }],
  reported_by: [{ required: true, message: 'Please enter reporting organization', trigger: 'blur' }],
  report_date: [{ required: true, message: 'Please select report date', trigger: 'change' }]
}

// Load donor list
const loadDonors = async () => {
  try {
    const data = await donorAPI.getList({ is_active: true, pageSize: 1000 })
    donorList.value = data.data || []
    console.log('Donor list:', donorList.value)
  } catch (error) {
    console.error('Failed to load donor list', error)
  }
}

// Load recipient list
const loadRecipients = async () => {
  try {
    const data = await recipientAPI.getList({ pageSize: 1000 })
    recipientList.value = data.data || []
    console.log('Recipient list:', recipientList.value)
  } catch (error) {
    console.error('Failed to load recipient list', error)
  }
}

// Load list data
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    const data = await offspringAPI.getList(params)
    offspringList.value = data.data || []
    pagination.total = data.count || 0
  } catch (error) {
    ElMessage.error('Failed to load data')
  } finally {
    loading.value = false
  }
}

// Search
const handleSearch = () => {
  pagination.page = 1
  loadData()
}

// Page change (do not reset page number)
const handlePageChange = () => {
  loadData()
}

// Reset
const handleReset = () => {
  Object.assign(searchForm, {
    donor_id: '',
    gender: ''
  })
  handleSearch()
}

// Add
const handleAdd = () => {
  dialogTitle.value = 'Add Offspring Record'
  Object.assign(formData, {
    offspring_id: null,
    donor_id: '',
    recipient_id: '',
    date_of_birth: '',
    gender: 'Male',
    reported_by: '',
    report_date: new Date()
  })
  dialogVisible.value = true
}

// Edit
const handleEdit = (row) => {
  dialogTitle.value = 'Edit Offspring Record'
  Object.assign(formData, row)
  dialogVisible.value = true
}

// Delete
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `Are you sure you want to delete offspring record ID: ${row.offspring_id}?`,
      'Warning',
      {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }
    )
    await offspringAPI.delete(row.offspring_id)
    ElMessage.success('Deleted successfully')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('Failed to delete')
    }
  }
}

// Submit form
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    console.log('Data to submit:', formData)
    
    if (formData.offspring_id) {
      await offspringAPI.update(formData.offspring_id, formData)
      ElMessage.success('Updated successfully')
    } else {
      const response = await offspringAPI.create(formData)
      console.log('Offspring created successfully:', response)
      ElMessage.success('Created successfully')
    }
    dialogVisible.value = false
    loadData()
  } catch (error) {
    console.error('Submission failed, detailed error:', error)
    console.error('Error response:', error.response)
    
    // Display detailed error message
    const errorMsg = error.response?.data?.message || error.message || 'Operation failed'
    ElMessage.error(errorMsg)
  }
}

// Format date
const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleDateString('en-US')
}

onMounted(async () => {
  console.log('Offspring tracking page loaded, URL params:', route.query)
  
  // Load data lists first
  await loadDonors()
  await loadRecipients()
  
  console.log('Donor list loaded, count:', donorList.value.length)
  console.log('Recipient list loaded, count:', recipientList.value.length)
  
  loadData()
  
  // Check if redirected from order page, if so, auto-open add dialog with pre-filled info
  if (route.query.action === 'add') {
    console.log('Add mode detected')
    console.log('Donor ID:', route.query.donorId, 'Type:', typeof route.query.donorId)
    console.log('Recipient ID:', route.query.recipientId, 'Type:', typeof route.query.recipientId)
    
    dialogTitle.value = 'Add Offspring Record'
    
    // Pre-fill donor
    if (route.query.donorId && route.query.donorId !== 'null' && route.query.donorId !== 'undefined') {
      const donorIdNum = parseInt(route.query.donorId)
      console.log('Converted donor ID:', donorIdNum)
      
      // Check if this ID exists in the list
      const donor = donorList.value.find(d => d.donor_id === donorIdNum)
      console.log('Found in donor list:', donor)
      
      formData.donor_id = donorIdNum
      console.log('Set formData.donor_id:', formData.donor_id)
    } else {
      console.warn('Invalid donor ID:', route.query.donorId)
    }
    
    // Pre-fill recipient
    if (route.query.recipientId && route.query.recipientId !== 'null' && route.query.recipientId !== 'undefined') {
      const recipientIdNum = parseInt(route.query.recipientId)
      console.log('Converted recipient ID:', recipientIdNum)
      
      // Check if this ID exists in the list
      const recipient = recipientList.value.find(r => r.recipient_id === recipientIdNum)
      console.log('Found in recipient list:', recipient)
      
      formData.recipient_id = recipientIdNum
      console.log('Set formData.recipient_id:', formData.recipient_id)
    } else {
      console.warn('Invalid recipient ID:', route.query.recipientId)
    }
    
    // Pre-fill report date as today
    formData.report_date = new Date()
    
    // Open dialog
    dialogVisible.value = true
    
    // Notify user
    ElMessage.info('Order-related information has been auto-filled. Please complete date of birth, gender, and other details.')
  }
})
</script>

<style scoped>
.offspring-list {
  padding: 0;
}

.page-title {
  font-size: 24px;
  font-weight: 500;
  margin-bottom: 20px;
  color: #303133;
}

.search-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
